using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CMS.Core.DataInterfaces;
using CMS.Data;
using CMS.Data.Common;
using CMS.Core.Domain;
using CMS.Presenters;

namespace CMS.Web.ListManager
{
    public partial class UserGroup : BaseUserControl, IUserGroupView
    {
        private UserGroupPresenter presenter;
        IList<NhomNguoiSuDung> gList;
        Boolean IsContinues = false;
        bool isRole = false;
        NguoiSuDungInfo userInfo;

        public UserGroup()
        {            
            this.presenter = new UserGroupPresenter(this, NHibernateDaoFactory.Instance.GetNhomNguoiSuDungDao());
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            presenter.UpdateCompleteEvent += new EventHandler(HandleUpdateCompleteEvent);
            presenter.CancelUpdateEvent += new EventHandler(HandleCancelUpdateEvent);
            presenter.DeleteCompleteEvent += new EventHandler(HandleDeleteCompleteEvent);
            if (Request.QueryString["Id"] != null)
            {
                this.presenter.InitViewForEditing(Request.QueryString.Get("Id").ToString(), false);
            }
        }

        private void HandleUpdateCompleteEvent(object sender, EventArgs e)
        {
            if (!this.IsContinues)
            {
                Response.Redirect(BaseUrlWithOnlyID + "&fName=10");
            }
            else {
                Response.Redirect(BaseUrlWithOnlyID + "&fName=10&action=ADD");
            }
        }

        private void HandleCancelUpdateEvent(object sender, EventArgs e)
        {
            Response.Redirect(BaseUrlWithOnlyID + "&fName=10");
        }

        private void HandleDeleteCompleteEvent(object sender, EventArgs e)
        {
            Response.Redirect(BaseUrlWithOnlyID + "&fName=10");
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            this.RaiseClientEvent();

            tblForm.Visible = (Request.QueryString["action"] != null);
            if (Request.QueryString["action"] == "EDIT") btnOKC.Visible = false;
            if (Request.QueryString["action"] != null) hrLine.Visible = true;
            userInfo = (NguoiSuDungInfo)Session["UserInfo"];
            presenter.LoadViewFromModel(tblForm.Visible, userInfo.ID);   
            if (!this.IsPostBack)
            {
                //this.presenter.LoadViewFromModel(tblForm.Visible, userInfo.ID);                
            }
            
           
        }

        protected void RaiseClientEvent()
        {
            btnDelete.Attributes.Add("onclick", "return doSetStatus(0);");
            btnAdd.Attributes.Add("onclick", "return AddNew();");
        }

        public IList<NhomNguoiSuDung> GroupList
        {
            set {
                gridObj.DataSource = value;
                gridObj.DataBind();
                this.gList = value;
            }
            get { return this.gList; }
        }

        public IList<VaiTro> VaiTroList
        {
            set
            {
                chkRoles.DataSource = value;
                chkRoles.DataBind();
            }
        }

        public IList<ChucNang> ChucNangList { 
            set {
                BuildTreeRoot(trvFunctions, value);
            } 
        }
        
        public String TenNhom
        {
            get { return this.txtName.Text.Trim(); }
            set { this.txtName.Text = value; }
        }

        public String MoTa
        {
            get { return this.txtDesc.Text.Trim(); }
            set { this.txtDesc.Text = value; }
        }

        public String VaiTro
        {
            get {
                String ids = "";
                foreach (ListItem item in chkRoles.Items)
                {
                    if (item.Selected) ids += (ids == "") ? item.Value : "," + item.Value;
                }
                return ids;
            }
            set {
                String[] ids = value.Split(new Char[] { ',' });
                for (int i = 0; i < ids.Length; i++)
                {
                    ListItem item = chkRoles.Items.FindByValue(ids[i]);
                    if (item != null) item.Selected = true;
                }
            }
        }

        public String MaChucNang {
            get {
                String ids = "";
                foreach (TreeNode node in trvFunctions.Nodes)
                {
                    if (node.Checked)
                    {
                        ids += (ids == "") ? node.Value : "," + node.Value;
                        String temp = GetCheckedNodeIds(node);
                        if (temp != "")
                        {
                            ids += "," + temp;
                        }
                    }
                }
                return ids;
            }
        }

        public IList<ChucNang> ChucNangs {
            set
            {
                foreach (TreeNode node in trvFunctions.Nodes)
                {
                    foreach (ChucNang cn in value)
                    {
                        if (node.Value == cn.ID.ToString())
                        {
                            node.Checked = true;
                            CheckExistNodes(node, value);
                        }
                    }
                }
            }
        }

        public Boolean TrangThai
        {
            get { return (this.radStatus.SelectedIndex == 0); }
            set { this.radStatus.SelectedIndex = value ? 0 : 1; }
        }

        public bool IsValid
        {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        private void BuildTreeRoot(TreeView trv, IList<ChucNang> cnList)
        {
            if (cnList.Count == 0)
                return;
            foreach (ChucNang cn in cnList)
            {
                if (cn.MaCapCha == 0)
                {
                    TreeNode nodetmp = new TreeNode(cn.TenChucNang, cn.ID.ToString());
                    nodetmp.Target = cn.ID.ToString();
                    trv.Nodes.Add(nodetmp);
                    nodetmp.ShowCheckBox = true;
                    nodetmp.SelectAction = TreeNodeSelectAction.None;
                    BuildTree(nodetmp, cnList);
                    //nodetmp.Expand();
                }
            }
        }

        private void BuildTree(TreeNode node, IList<ChucNang> cnList)
        {
            if (cnList.Count == 0)
                return;
            foreach (ChucNang cn in cnList)
            {
                if (cn.MaCapCha.ToString() == node.Value)
                {
                    TreeNode nodetmp = new TreeNode(cn.TenChucNang, cn.ID.ToString());
                    nodetmp.Target = cn.ID.ToString();
                    nodetmp.ShowCheckBox = true;
                    nodetmp.SelectAction = TreeNodeSelectAction.None;
                    node.ChildNodes.Add(nodetmp);
                    BuildTree(nodetmp, cnList);
                    //nodetmp.Expand();
                }
            }
        }

        private void CheckExistNodes(TreeNode parent, IList<ChucNang> cnList)
        {
            foreach (TreeNode node in parent.ChildNodes)
            {
                foreach (ChucNang cn in cnList)
                {
                    if (node.Value == cn.ID.ToString())
                    {
                        node.Checked = true;
                        CheckExistNodes(node, cnList);
                    }
                }

            }
        }

        private String GetCheckedNodeIds(TreeNode parent)
        {
            String ids = "";
            foreach (TreeNode node in parent.ChildNodes)
            {
                if (node.Checked)
                {
                    ids += (ids == "") ? node.Value : "," + node.Value;
                    String temp = GetCheckedNodeIds(node);
                    if (temp != "")
                    {
                        ids += "," + temp;
                    }
                }
            }
            return ids;
        }


        protected void btnOK_Click(object sender, EventArgs e)
        {
            presenter.UpdateObject();
        }

        protected void btnOKC_Click(object sender, EventArgs e)
        {
            this.IsContinues = true;
            presenter.UpdateObject();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.presenter.CancelUpdate();
        }

        protected void gridObj_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gridObj.DataSource = this.GroupList;
            gridObj.PageIndex = e.NewPageIndex;
            gridObj.DataBind();

        }

        protected void gridObj_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Pager)
            {
                
                // Disabled control 
                foreach (GridViewRow row in gridObj.Rows)
                {
                    NhomNguoiSuDung obj = NhomNguoiSuDungDao.Instance.GetById(Convert.ToByte(gridObj.DataKeys[row.RowIndex].Value));
                    if (!obj.TrangThai)
                    {
                        CheckBox cb = (CheckBox)row.FindControl("chkSelect");
                        cb.Enabled = false;
                    }
                }
                foreach (Control c in e.Row.Cells[0].Controls)
                {
                    if (c.GetType().ToString().Equals("System.Web.UI.WebControls.PagerTable"))
                    {
                        Table tbl = (Table)c;
                        TableCell cell = new TableCell();
                        cell.Text = "Trang ";
                        cell.HorizontalAlign = HorizontalAlign.Right;
                        tbl.Rows[0].Cells.AddAt(0, cell);
                    }
                }
            }
        }

        // For Delete button
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string ids = "";
            foreach (GridViewRow row in gridObj.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("chkSelect");
                if (cb.Checked)
                {
                    ids +=(ids == "" ? "" : ",") + Convert.ToString(gridObj.DataKeys[row.RowIndex].Value);
                }
            }
            if (ids != "")
            {
                this.presenter.ChangeObjectsStatus(ids);
            }
        }


        #region IUserGroupView Members


        public bool IsRole
        {
            get
            {
                return this.isRole;
            }
            set
            {
                this.isRole = value;
                this.btnAdd.Visible = value;
                this.btnDelete.Visible = value;
            }
        }

        #endregion
    }
}